package org.example.listener;

import org.example.service.RedisSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

@Component
public class WebSocketEventListener {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Autowired
    private RedisSessionService redisSessionService;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = headerAccessor.getSessionId();
        
        // 从连接属性中获取用户ID
        String userId = (String) headerAccessor.getSessionAttributes().get("userId");
        
        if (userId != null) {
            redisSessionService.registerUserSession(userId, sessionId);
            logger.info("用户 {} 连接成功, Session ID: {}", userId, sessionId);
        } else {
            logger.warn("匿名用户连接, Session ID: {}", sessionId);
        }
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = headerAccessor.getSessionId();
        String userId = (String) headerAccessor.getSessionAttributes().get("userId");
        
        if (userId != null) {
            redisSessionService.removeUserSession(userId);
            logger.info("用户 {} 断开连接, Session ID: {}", userId, sessionId);
        } else {
            logger.info("匿名用户断开连接, Session ID: {}", sessionId);
        }
    }

    @EventListener
    public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String destination = headerAccessor.getDestination();
        String sessionId = headerAccessor.getSessionId();
        String userId = (String) headerAccessor.getSessionAttributes().get("userId");
        
        if (userId != null) {
            logger.info("用户 {} 订阅了频道: {}, Session ID: {}", userId, destination, sessionId);
        } else {
            logger.info("匿名用户订阅了频道: {}, Session ID: {}", destination, sessionId);
        }
    }
}